package com.caipiao.controller;

import com.alibaba.druid.sql.ast.statement.SQLUpdateSetItem;
import com.caipiao.mapper.SIntegralMapper;
import com.caipiao.mapper.SPlanMapper;
import com.caipiao.mapper.SUserMapper;
import com.caipiao.mapper.SUserPlanItemRecordMapper;
import com.caipiao.pojo.*;
import com.caipiao.service.UserService;
import com.caipiao.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2019/1/6.
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private SUserMapper sUserMapper;
    @Autowired
    private SUserPlanItemRecordMapper sUserPlanItemRecordMapper;
    @Autowired
    private SIntegralMapper sIntegralMapper;
    @Autowired
    private SPlanMapper sPlanMapper;

    /**
     * 登录
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/login" ,method = RequestMethod.POST)
    @ResponseBody
    public ObjectResult login(XMLBean xmlBean){
        if(StringUtil.isEmpty(xmlBean.getMobile())|| StringUtil.isEmpty(xmlBean.getPassword())){
            return ObjectResult.build("0","参数丢失，请重试");
        }
        return userService.login(xmlBean);
    }


    /**
     * 注册
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/regist" ,method = RequestMethod.POST)
    @ResponseBody
    public ObjectResult regist(XMLBean xmlBean, HttpServletResponse response){
        if(StringUtil.isEmpty(xmlBean.getMobile())|| StringUtil.isEmpty(xmlBean.getPassword())){
            return ObjectResult.build("0","参数丢失，请重试");
        }
        response.setHeader("Access-Control-Allow-Origin", "*");
        return userService.regist(xmlBean);
    }

    /**
     * 退出登录
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/logout" ,method = RequestMethod.POST)
    @ResponseBody
    public ObjectResult logout(XMLBean xmlBean){

        return ObjectResult.build("1","成功");
    }

    /**
     * 忘记密码
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ObjectResult updatePassword(XMLBean xmlBean){
        if (StringUtil.isEmpty(xmlBean.getMobile()) ||StringUtil.isEmpty(xmlBean.getPassword())){
            return ObjectResult.build("0","参数丢失，请重试");
        }
        return userService.updatePassword(xmlBean);
    }

    /**
     * 我的账户
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/index" ,method = RequestMethod.POST)
    @ResponseBody
    public ObjectResult index(XMLBean xmlBean){
        if(StringUtil.isEmpty(xmlBean.getToken())){
            return ObjectResult.build("0","未登录");
        }
        String userId = CommonUtils.decToken(xmlBean.getToken());
        SUser sUser = sUserMapper.selectByPrimaryKey(Integer.parseInt(userId));
        sUser.setTotal(sUser.getAccountAble()+sUser.getFrozen());
        sUser.setOpen(1);
        sUser.setIsNewVersion(0);
        sUser.setVersionCode(11);

        //累计中奖积分
        SIntegral sIntegral = new SIntegral();
        sIntegral.setUser_id(Integer.parseInt(userId));
        sIntegral.setType(4);
        Float winning = sIntegralMapper.selectSumIntegral(sIntegral);
            sUser.setWinning(winning==null?  0:winning);

        //累计奖励积分
        sIntegral.setType(7);
        Float reward = sIntegralMapper.selectSumIntegral(sIntegral);
        sUser.setReward(reward==null?  0:reward);

        return ObjectResult.build("1","成功",sUser);
    }

    /**
     * 修改个人信息
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ObjectResult updateInform(XMLBean xmlBean, HttpServletRequest request){
        if (StringUtil.isEmpty(xmlBean.getToken())){
            return ObjectResult.build("0","未登录");
        }
        return userService.update(xmlBean,request);
    }

    /**
     * 我的订单
     * @param xmlBean
     * @return
     */

    @RequestMapping(value = "/order" ,method = RequestMethod.POST)
    @ResponseBody
    public ObjectResult order(XMLBean xmlBean){
        if(StringUtil.isEmpty(xmlBean.getToken())){
            return ObjectResult.build("0","未登录");
        }
        String userId = CommonUtils.decToken(xmlBean.getToken());
        List<SUserPlanItemRecord> sUserPlanItemRecords = sUserPlanItemRecordMapper.selectByUserId(Integer.parseInt(userId));

        Page<SUserPlanItemRecord> page = new Page<>();
        page.setP(xmlBean.getP()==null? 0 :xmlBean.getP());
        List<SUserPlanItemRecord> pageContent = page.getPageContent(sUserPlanItemRecords);

        for (SUserPlanItemRecord sUserPlanItemRecord:pageContent){
            sUserPlanItemRecord.setHead(ConfigUtils.ADMIN_URL+sUserPlanItemRecord.getHead());
            sUserPlanItemRecord.setTitle(sUserPlanItemRecord.getTitle()+"("+sUserPlanItemRecord.getPayCount()+"份)");
        }

        Map<String, Object> map = new HashMap<>();
        map.put("list",pageContent);
        map.put("count",page.getPageTotal());

        return ObjectResult.build("1","成功",map);
    }


    /**
     * 订单详情
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/orderDetails" ,method = RequestMethod.POST)
    @ResponseBody
    public ObjectResult orderDetails(XMLBean xmlBean){
        if(StringUtil.isEmpty(xmlBean.getToken()) || StringUtil.isEmpty(xmlBean.getId())){
            return ObjectResult.build("0","参数丢失，请重试");
        }
        String userId = CommonUtils.decToken(xmlBean.getToken());
        Map<String,Object> map = new HashMap<>();
        map.put("userId",userId);
        map.put("planId",xmlBean.getId());
        List<SIntegral> sIntegrals = sIntegralMapper.selectIntegralByUserId(map);

        Page<SIntegral> page = new Page<>();
        page.setP(xmlBean.getP()==null? 1:xmlBean.getP());
        List<SIntegral> pageContent = page.getPageContent(sIntegrals);

        for (SIntegral s:pageContent){
            s.setAddTime(s.getAddTime().substring(0,s.getAddTime().lastIndexOf(".")));
            String title = "";
            if (s.getPlan_id()!=0) {
                title = sPlanMapper.selectByPrimaryKey(s.getPlan_id()).getTitle();
            }
            switch (s.getType()){
                case 1:
                    s.setTitle("清账");break;
                case 2:
                    s.setTitle(title+"投注");break;
                case 3:
                    s.setTitle("储值");break;
                case 4:
                    s.setTitle(title+"中奖积分");break;
                case 5:
                    s.setTitle(title+"返还的冻结积分");break;
                case 6:
                    s.setTitle(title+"比赛使用积分");break;
                case 7:
                    s.setTitle(title+"佣金");break;
                default:
                    break;
            }
        }

        map.clear();
        map.put("list",pageContent);

        return ObjectResult.build("1","成功",map);
    }



    /**
     * 邀请页面
     * @param xmlBean
     * @return
     */
    @RequestMapping("/invite")
    @ResponseBody
    public ObjectResult invite(XMLBean xmlBean){
        if(StringUtil.isEmpty(xmlBean.getToken())){
            return ObjectResult.build("0","未登录");
        }
        Map<String,Object> data = new HashMap<String,Object>();
        String userId = CommonUtils.decToken(xmlBean.getToken());
        SUser sUser = sUserMapper.selectByPrimaryKey(Integer.parseInt(userId));

        data.put("title","推荐您使用乐彩星球，专家方案中奖率高！快来一起玩足球彩票吧！");
        data.put("content","［乐彩星球］高中奖率！实体彩票店出票！玩转足球竞技彩！");
        data.put("url", ConfigUtils.SYS_URL+"index/regist?title="+sUser.getSalt());

        return ObjectResult.build("1","成功",data);
    }

    /**
     * 积分列表
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/integral_list", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ObjectResult integral_list(XMLBean xmlBean){
        Map<String,Object> data = new HashMap<String,Object>();
        if(xmlBean.getToken()==null||xmlBean.getToken().equals(""))  return ObjectResult.build("0","token不存在");
        String userId = CommonUtils.decToken(xmlBean.getToken());
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("userId",userId);
        if ("1".equals(xmlBean.getType())){
            map.put("type","(1)");
        }
        if ("3".equals(xmlBean.getType())){
            map.put("type","(3)");
        } if ("2".equals(xmlBean.getType())){
            map.put("type","(2,4,5,6,7)");
        }if("4".equals(xmlBean.getType())){
            map.put("type","(8,9)");
        }
        List<SIntegral> integrals = sIntegralMapper.selectIntegralByUserId(map);
        Page<SIntegral> page = new Page<>();
        page.setP(xmlBean.getP()==null? 1:xmlBean.getP());
        page.setPageSize(10);
        List<SIntegral> content = page.getPageContent(integrals);
        for (SIntegral s:content){
            s.setAddTime(s.getAddTime().substring(0,s.getAddTime().lastIndexOf(".")));
            String title = "";
            if (s.getPlan_id()!=0) {
                title = sPlanMapper.selectByPrimaryKey(s.getPlan_id()).getTitle();
            }
            switch (s.getType()){
                case 1:
                    s.setTitle("清账");break;
                case 2:
                    s.setTitle(title+"投注");break;
                case 3:
                    s.setTitle("储值");break;
                case 4:
                    s.setTitle(title+"中奖积分");break;
                case 5:
                    s.setTitle(title+"返还的冻结积分");break;
                case 6:
                    s.setTitle(title+"比赛使用积分");break;
                case 7:
                    s.setTitle(title+"佣金");break;
                case 8:
                    s.setTitle("商城消费积分");break;
                case 9:
                    s.setTitle("订单取消");break;
                default:
                    break;
            }
        }

        SUser sUser = sUserMapper.selectByPrimaryKey(Integer.parseInt(userId));
        data.clear();
        data.put("list",content);
        data.put("integral",sUser.getAccountAble());
        data.put("count",page.getPageTotal());

        return ObjectResult.build("1","成功",data);
    }

    /**
     * 微信登录
     * @param xmlBean
     * @param request
     * @return
     */
    @RequestMapping(value = "/weixinLogin", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ObjectResult weixinLogin(XMLBean xmlBean,HttpServletRequest request){
        if(StringUtil.isEmpty(xmlBean.getWxId())){
            return ObjectResult.build("0","微信id为空");
        }

        return userService.weixinLogin(xmlBean,request);
    }

    /**
     * 绑定手机号
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/bindingMobile", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ObjectResult bindingMobile(XMLBean xmlBean,HttpServletRequest request){

        return userService.bindingMobile(xmlBean,request);
    }

    /**
     * 推广记录
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/inviteRecord", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ObjectResult inviteRecord(XMLBean xmlBean){
        String userId = CommonUtils.decToken(xmlBean.getToken());

        List<SUser> sUsers = sUserMapper.selectInvitByUserId(userId);
        Page<SUser> page = new Page();
        page.setP(xmlBean.getP()==null ? 1 :xmlBean.getP());
        List<SUser> pageContent = page.getPageContent(sUsers);
        for (SUser sUser:pageContent){
          sUser.setMobile(CommonUtils.concealMobile(sUser.getMobile()));
        }

        Map<String,Object> map = new HashMap<>();
        map.put("list",pageContent);
        map.put("count",page.getPageTotal());

        return ObjectResult.build("1","成功",map);
    }
}
